﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using VAdvantage.Classes;
using VAdvantage.Common;
using VAdvantage.Process; using VAdvantage.ProcessEngine;
using VAdvantage.Model;
using VAdvantage.DataBase;
using VAdvantage.SqlExec;
using VAdvantage.Utility;
using VAdvantage.Controls;
using System.Data;
using System.Data.SqlClient;
using VAdvantage.Logging;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Threading;
using System.Collections.ObjectModel;

namespace VAdvantage.Grids
{
    public class VCreateFromStatement : VCreateFrom
    {
        #region private Variables
        private static VLogger _log = VLogger.GetVLogger(typeof(VCreateFromStatement).FullName);
        //list to add grid header columns
        protected static DataGridColumn[] arrList1 = null;
        DataSet _mainData = null;

        #endregion

        /// <summary>
        ///  Protected Constructor
        /// </summary>
        /// <param name="mTab">Mtab</param>
        public VCreateFromStatement(GridTab mTab)
            : base(mTab)
        {
            _log.Info("");

        }

        /// <summary>
        /// Dynamic Init
        /// </summary>
        /// <returns>true if initialized</returns>
        protected override bool DynInit()
        {
            if (_mTab.GetValue("C_BankStatement_ID") == null)
            {
                ShowMessage.Error("", true, Msg.GetMsg(Envs.GetContext(), "SaveErrorRowNotFound", true).ToString());
                return false;
            }
            //  Set Default
            int C_BankAccount_ID = Envs.GetContext().GetContextAsInt(_WindowNo, "C_BankAccount_ID");
            this.Title = Msg.Translate(Envs.GetContext(), "C_BankStatement_ID") + " .. " + Msg.Translate(Envs.GetContext(), "CreateFrom");

            ThreadPool.QueueUserWorkItem(delegate
           {
               int AD_Column_ID = 4917;        //  C_BankStatement.C_BankAccount_ID
               MLookup lookup = MLookupFactory.Get(Envs.GetContext(), _WindowNo, AD_Column_ID, DisplayType.TableDir);
               //  Get StatementDate
               DateTime ts = Convert.ToDateTime(_mTab.GetValue("StatementDate"));
               DataSet data = GetBankAccountData(Envs.GetContext(), C_BankAccount_ID, ts);
               _mainData = data;
               //  initial Loading
               //LoadBankAccount(C_BankAccount_ID, data);
               System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => InvoKFunction(lookup, C_BankAccount_ID, data));
           });
            return true;
        }

        private void InvoKFunction(Lookup lookup, int C_BankAccount_ID, DataSet data)
        {
            cmbBankAccount = new VComboBox("C_BankAccount_ID", true, false, true, lookup, 150);
            cmbBankAccount.SelectedValue = null;
            cmbBankAccount.SelectedValue = C_BankAccount_ID;
            GetTableFieldVOs(data);
            if (cmbBankAccount != null)
            {
                cmbBankAccount.Width = 180;
                //tablePanel.Controls.Add(lblBankAccount, 0, 0);
                tablePanel.Children.Add(lblBankAccount);
                lblBankAccount.Margin = new Thickness(3);
                Grid.SetColumn(lblBankAccount, 0);
                Grid.SetRow(lblBankAccount, 0);

                //tablePanel.Controls.Add(cmbBankAccount, 1, 0);
                tablePanel.Children.Add(cmbBankAccount);
                cmbBankAccount.Margin = new Thickness(3);
                Grid.SetColumn(cmbBankAccount, 1);
                Grid.SetRow(cmbBankAccount, 0);
            }
            
            this.cmbBankAccount.SelectionChanged += new SelectionChangedEventHandler(cmbBankAccount_SelectionChanged);
        }

        /// <summary>
        /// Init Details (never called)
        /// </summary>
        /// <param name="C_BPartner_ID">BPartner</param>
        protected override void InitBPDetails(int C_BPartner_ID, List<NamePair> invoice, List<NamePair> shipments)
        {
        }

        /// <summary>
        /// create grid header columns
        /// </summary>
        /// <param name="ctx">context</param>
        /// <returns></returns>
        public void GetTableFieldVOs(DataSet data)
        {
            //new list for header
            Ctx ctx = Envs.GetCtx();
            // clear and unbind the grid
            vdgvRecords.DataContext = null;
            vdgvRecords.ItemsSource = null;
            //vdgvQuery.DataBindings.Clear();
            vdgvRecords.Columns.Clear();
            vdgvRecords.AutoGenerateColumns = false;

            //1
            Grids.MyDataGridCheckBoxColumn chk = new MyDataGridCheckBoxColumn();
            chk.Header = Msg.GetMsg(Envs.GetCtx(), "SELECTROW");
            chk.Binding = new System.Windows.Data.Binding("SELECTROW");
            //chk.DataPropertyName = "SELECTROW";
            //chk.DataGridView = vdgvRecords;
            chk.DataGrid = vdgvRecords;
            chk.IsThreeState = false;
            chk.IsReadOnly = false;
            chk.Click += new RoutedEventHandler(chk_Click);
            vdgvRecords.Columns.Add(chk);

            //2
            DataGridTextColumn txt = new DataGridTextColumn();
            txt.Header = Msg.Translate(Envs.GetCtx(), "DATE");
            txt.Binding = new System.Windows.Data.Binding("DATETRX");
            txt.IsReadOnly = true;
            vdgvRecords.Columns.Add(txt);

            //3
            DataGridTextColumn txt1 = new DataGridTextColumn();
            txt1.Header = Msg.Translate(Envs.GetCtx(), "C_PAYMENT_ID");
            txt1.Binding = new System.Windows.Data.Binding("C_PAYMENT_ID");
            txt1.IsReadOnly = true;
            vdgvRecords.Columns.Add(txt1);

            //DOCUMENTNO
            DataGridTextColumn docNo = new DataGridTextColumn();
            docNo.Header = Msg.Translate(Envs.GetCtx(), "C_PAYMENT_ID");
            docNo.Binding = new System.Windows.Data.Binding("DOCUMENTNO");
            docNo.IsReadOnly = true;
            vdgvRecords.Columns.Add(docNo);

            //4
            DataGridTextColumn curncy = new DataGridTextColumn();
            curncy.Header = Msg.Translate(Envs.GetCtx(), "C_CURRENCY_ID");
            curncy.Binding = new System.Windows.Data.Binding("C_CURRENCY_ID");
            curncy.IsReadOnly = true;
            vdgvRecords.Columns.Add(curncy);

            //ISO_CODE
            DataGridTextColumn iso = new DataGridTextColumn();
            iso.Header = Msg.Translate(Envs.GetCtx(), "C_CURRENCY_ID");
            iso.Binding = new System.Windows.Data.Binding("ISO_CODE");
            iso.IsReadOnly = true;
            vdgvRecords.Columns.Add(iso);

            //5
            DataGridTextColumn txt3 = new DataGridTextColumn();
            txt3.Header = Msg.Translate(Envs.GetCtx(), "AMOUNT");
            txt3.Binding = new System.Windows.Data.Binding("AMOUNT");
            txt3.IsReadOnly = true;
            vdgvRecords.Columns.Add(txt3);

            //5
            DataGridTextColumn txt4 = new DataGridTextColumn();
            txt4.Header = Msg.Translate(Envs.GetCtx(), "CONVERTEDAMOUNT");
            txt4.Binding = new System.Windows.Data.Binding("CONVERTEDAMOUNT");
            txt4.IsReadOnly = true;
            vdgvRecords.Columns.Add(txt4);

            //6
            DataGridTextColumn txt5 = new DataGridTextColumn();
            txt5.Header = Msg.Translate(Envs.GetCtx(), "C_BPARTNER_ID");
            txt5.Binding = new System.Windows.Data.Binding("C_BPARTNER_ID");
            txt5.IsReadOnly = true;
            vdgvRecords.Columns.Add(txt5);

            DataGridTextColumn name = new DataGridTextColumn();
            name.Header = Msg.Translate(Envs.GetCtx(), "C_BPARTNER_ID");
            name.Binding = new System.Windows.Data.Binding("NAME");
            name.IsReadOnly = true;
            vdgvRecords.Columns.Add(name);

            // if user has given any dataset
            if (data != null)
            {
                // bind grid to dataset values
                vdgvRecords.ItemsSource = data.Tables[0].GetBindableData(new Connector());
                mainDataSet = data;
            }
            vdgvRecords.Columns[2].Visibility = System.Windows.Visibility.Collapsed;
            vdgvRecords.Columns[4].Visibility = System.Windows.Visibility.Collapsed;
            // vdgvRecords.Columns[6].Visibility = System.Windows.Visibility.Collapsed;
            vdgvRecords.Columns[8].Visibility = System.Windows.Visibility.Collapsed;
            // vdgvRecords.Columns[9].Visibility = System.Windows.Visibility.Collapsed;
            base.statusBar.SetStatusLine(Msg.GetMsg(Envs.GetCtx(), "NumberOfRows") + data.Tables[0].Rows.Count.ToString());
            gridCount = 0;
        }

        //void chk_Click(object sender, RoutedEventArgs e)
        //{

        //}

        /// <summary>
        /// get account data
        /// </summary>
        /// <param name="ctx">context</param>
        /// <param name="C_BankAccount_ID">id</param>
        /// <param name="ts">date</param>
        /// <returns>array list of data</returns>
        public static DataSet GetBankAccountData(Context ctx, int C_BankAccount_ID, DateTime ts)
        {
            if (ts == null)
            {
                ts = DateTime.Today.Date;
            }
            //String sql = "SELECT p.DateTrx,p.C_Payment_ID,p.DocumentNo, p.C_Currency_ID,c.ISO_Code, p.PayAmt,"
            //    + "currencyConvert(p.PayAmt,p.C_Currency_ID,ba.C_Currency_ID,'" + ts + "',null,p.AD_Client_ID,p.AD_Org_ID),"   //  #1
            //    + " bp.Name "

            String sql = "SELECT p.DateTrx as DATETRX,"
                    + " p.C_Payment_ID as C_PAYMENT_ID,"
                    + " p.DocumentNo  as DOCUMENTNO,"
                    + "  p.C_Currency_ID as C_CURRENCY_ID,"
                    + "  c.ISO_Code as ISO_CODE,"
                    + " p.PayAmt   as AMOUNT,"
                    + "  currencyConvert(p.PayAmt,p.C_Currency_ID,ba.C_Currency_ID," + DataBase.DB.TO_DATE(ts) + ",NULL,p.AD_Client_ID,p.AD_Org_ID) as CONVERTEDAMOUNT,"
                    + " bp.c_bpartner_id as C_BPARTNER_ID,"
                    + " bp.Name as NAME,'false' as SELECTROW  "
                + " FROM C_BankAccount ba"
                + " INNER JOIN C_Payment_v p ON (p.C_BankAccount_ID=ba.C_BankAccount_ID)"
                + " INNER JOIN C_Currency c ON (p.C_Currency_ID=c.C_Currency_ID)"
                + " LEFT OUTER JOIN C_BPartner bp ON (p.C_BPartner_ID=bp.C_BPartner_ID) "
                + "WHERE p.Processed='Y' AND p.IsReconciled='N'"
                + " AND p.DocStatus IN ('CO','CL','RE','VO') AND p.PayAmt<>0"
                + " AND p.C_BankAccount_ID=" + C_BankAccount_ID                              	//  #2
                + " AND NOT EXISTS (SELECT * FROM C_BankStatementLine l "
                //	Voided Bank Statements have 0 StmtAmt
                    + "WHERE p.C_Payment_ID=l.C_Payment_ID AND l.StmtAmt <> 0)";
            DataSet ds = null;
            try
            {
                ds = DB.ExecuteDataset(sql, null, null);
            }
            catch (Exception e)
            {
                _log.Log(Level.SEVERE, sql, e);
            }
            return ds;
        }

        /// <summary>
        /// Load Data - Bank Account
        /// </summary>
        /// <param name="C_BankAccount_ID">Bank Account</param>
        //private void LoadBankAccount(int C_BankAccount_ID)
        //{
        //    _log.Config("C_BankAccount_ID=" + C_BankAccount_ID);
        //    /**
        //     *  Selected        - 0
        //     *  Date            - 1
        //     *  C_Payment_ID    - 2
        //     *  C_Currenncy     - 3
        //     *  Amt             - 4
        //     */

        //    //  Header Info
        //    GetTableFieldVOs(Envs.GetContext());


        //    for (int i = 0; i < arrList1.Length; i++)
        //    {
        //        vdgvRecords.Columns.Add(arrList1[i]);
        //    }
        //    if (data != null && data.Count > 0)
        //    {
        //        for (int i = 0; i < data.Count; i++)
        //        {
        //            try
        //            {
        //                //vdgvRecords.Rows.Add(1);

        //                dt.Rows.Add(new DataRow());

        //                ArrayList lst2 = (ArrayList)data[i];
        //                for (int j = 0; j < vdgvRecords.Columns.Count; j++)
        //                {

        //                    //vdgvRecords.Rows[i].Cells[j].Value = lst2[j];
        //                    dt.Rows[i][j] = lst2[j];
        //                }
        //                //vdgvRecords.Rows.Add(1);
        //            }
        //            catch
        //            {
        //            }
        //            ds.Tables[0] = dt;
        //            vdgvRecords.DataContext = ds.Tables[0];

        //        }
        //    }

        //    //vdgvRecords.AutoSize = true;
        //}

        /// <summary>
        /// List total amount
        /// </summary>
        protected override void Info()
        {
            //VDataGrid model = base.vdgvRecords;
            int rows = _mainData.Tables[0].Rows.Count;// GlobalVariable.GridRowsCount(base.vdgvRecords);
            Decimal total = Envs.ZERO;//0.0
            int count = 0;
            for (int i = 0; i < rows; i++)
            {
                //if (Convert.ToBoolean(Model.Rows[i].Cells[0].Value))
                if (Convert.ToBoolean(_mainData.Tables[0].Rows[i][0]))
                {
                    total = Decimal.Add(total, Convert.ToDecimal(_mainData.Tables[0].Rows[i]["AMOUNT"]));
                    count++;
                }
            }
            base.statusBar.SetStatusLine(count.ToString() + " - " + Msg.Translate(Envs.GetContext(), "Sum") + "  " + total.ToString());
            gridCount = count;
        }

        /// <summary>
        /// Save Statement - Insert Data
        /// </summary>
        /// <returns>true if saved</returns>
        protected override bool Save()
        {
            base.btnOk.IsEnabled = false;
            _log.Config("");
            //IList list = base.vdgvRecords.SelectedItems;
            //  fixed values
            int C_BankStatement_ID = Convert.ToInt32(_mTab.GetValue("C_BankStatement_ID"));//.intValue();
            //return SaveData(Envs.GetContext(), list, C_BankStatement_ID);
            ThreadPool.QueueUserWorkItem(delegate
            {
                SaveData(Envs.GetContext(), mainDataSet, C_BankStatement_ID);
                Dispatcher.BeginInvoke(delegate
                {
                    base.DialogResult=true;
            });
            });
            return true;
        }

        /// <summary>
        /// Save selected data
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="model"></param>
        /// <param name="C_BankStatement_ID"></param>
        /// <returns></returns>
        public static bool SaveData(Context ctx, DataSet ds, int C_BankStatement_ID)
        {
            List<DataRow> collection = new List<DataRow>();
            if (ds != null)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    if (ds.Tables[0].Rows[i]["SELECTROW"].ToString().ToUpper() == "TRUE")
                    {
                        collection.Add(ds.Tables[0].Rows[i]);
                    }
                }
            }
            else
            {
                return false;
            }

            //int rows = ds.Tables[0].Rows.Count;
            int rows = collection.Count;
            if (rows == 0)
            {
                return false;
            }
         
             MBankStatement bs = new MBankStatement(ctx, C_BankStatement_ID, null);
             _log.Config(bs.ToString());
             //  Lines
             for (int i = 0; i < rows; i++)
             {
                 //if (Convert.ToBoolean((bool)Model.Rows[i].Cells[0].Value))
                 if (true) //if (Convert.ToBoolean((bool)Convert.ToBoolean(((BindableObject)list[i]).GetValue("SELECT"))))
                 {
                     DateTime trxDate = Convert.ToDateTime(collection[i].ItemArray["DATETRX"].Value);//.getValueAt(i, 1);  //  1-DateTrx
                     //KeyNamePair pp = (KeyNamePair)dt.Rows[i][2];//.getValueAt(i, 2);   //  2-C_Payment_ID
                     //int C_Payment_ID = pp.GetKey();
                     int C_Payment_ID = Convert.ToInt32(collection[i].ItemArray["C_PAYMENT_ID"].Value);
                     //pp = (KeyNamePair)dt.Rows[i][3];//.getValueAt(i, 3);               //  3-Currency
                     //int C_Currency_ID = pp.GetKey();
                     int C_Currency_ID = Convert.ToInt32(collection[i].ItemArray["C_CURRENCY_ID"].Value);
                     //Decimal TrxAmt = Convert.ToDecimal(dt.Rows[i][4]);//.getValueAt(i, 4); //  4-PayAmt
                     Decimal TrxAmt = Convert.ToDecimal(collection[i].ItemArray["AMOUNT"].Value);
                     _log.Fine("Line Date=" + trxDate
                         + ", Payment=" + C_Payment_ID + ", Currency=" + C_Currency_ID + ", Amt=" + TrxAmt);
                     //	
                     MBankStatementLine bsl = new MBankStatementLine(bs);
                     bsl.SetStatementLineDate(trxDate);
                     bsl.SetPayment(new MPayment(ctx, C_Payment_ID, null));
                     if (!bsl.Save())
                     {
                         _log.Log(Level.SEVERE, "Line not created #" + i);
                     }
                 }   //   if selected
             }   //  for all rows
        // });
            return true;
        }

        /// <summary>
        ///on combo value change event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void cmbBankAccount_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            vdgvRecords.DataContext = null;
            vdgvRecords.ItemsSource = null;
            vdgvRecords.Columns.Clear();
            _log.Config(e.ToString());

            //  BankAccount
            KeyNamePair pp = (KeyNamePair)cmbBankAccount.SelectedItem;
            if (pp == null || pp.GetKey() == 0)
            {
                ;
            }
            else
            {
                int C_BankAccount_ID = pp.GetKey();

                //  set Order and Shipment to Null
                //LoadBankAccount(C_BankAccount_ID);

                ThreadPool.QueueUserWorkItem(delegate
                {
                    DateTime ts = Convert.ToDateTime(_mTab.GetValue("StatementDate"));
                    DataSet data = GetBankAccountData(Envs.GetContext(), C_BankAccount_ID, ts);
                    _mainData = data;
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() => GetTableFieldVOs(data));
                });

            }
        }

        /// <summary>
        /// overrid current form design over base class design
        /// </summary>
        protected override void JbInit()
        {
            Init();
            lblBankAccount.Content = Msg.Translate(Envs.GetContext(), "C_BankAccount_ID");

            //tablePanel.AutoSize = true;

            buttonImage = new Image();
            buttonImage.Source = Envs.LoadImageSource("checkedButton.PNG");
            btnSelectAllButton.Content = buttonImage;


            //  Lookup _value = MLookupFactory.Get(Envs.GetContext(), _WindowNo, 3499, DisplayType.Search);
            //  vBPartner = new VTextBoxButton("C_BPartner_ID", false, false, true, DisplayType.Search, _value);
        }

        /// <summary>
        /// table design setting
        /// </summary>
        protected override void InfoSetting()
        {
            //parameter panel   
            //this.tablePanel.ColumnCount = 2;
            ////this.tablePanel.CellBorderStyle = System.Windows.Forms.TableLayoutPanelCellBorderStyle.Outset;
            //this.tablePanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 35F));
            //this.tablePanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 45F));
            //this.tablePanel.Dock = System.Windows.Forms.DockStyle.Fill;
            //this.tablePanel.Location = new System.Drawing.Point(0, 0);
            ////this.tablePanel.Margin = new System.Windows.Forms.Padding(0);
            //this.tablePanel.RowCount = 1;
            //this.tablePanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
            //this.tablePanel.Size = new System.Drawing.Size(592, 30);
            //this.tablePanel.TabIndex = 1;

            ////bottom panel
            //this.bottomPanel.ColumnCount = 3;
            //this.bottomPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F));
            //this.bottomPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 62F));
            //this.bottomPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 62F));

            //this.bottomPanel.Dock = System.Windows.Forms.DockStyle.Fill;
            //this.bottomPanel.Location = new System.Drawing.Point(0, 308);
            ////this.bottomPanel.Margin = new System.Windows.Forms.Padding(0);
            //this.bottomPanel.Margin = new Padding(0, 5, 0, 0);
            //this.bottomPanel.Name = "bottomPanel";
            //this.bottomPanel.RowCount = 1;
            //this.bottomPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F));
            ////this.bottomPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 70F));
            //this.bottomPanel.Size = new System.Drawing.Size(606, 100);
            //this.bottomPanel.TabIndex = 3;

            ////DataGrid view setting
            //vdgvRecords.RowHeadersWidthSizeMode = System.Windows.Forms.DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;
            //vdgvRecords.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            ////vdgvRecords.BackgroundColor = System.Drawing.Color.Red;
            //this.vdgvRecords.Dock = System.Windows.Forms.DockStyle.Fill;

            //this.vdgvRecords.Location = new System.Drawing.Point(0, 48);
            //this.vdgvRecords.Margin = new System.Windows.Forms.Padding(0);
            //this.vdgvRecords.Size = new System.Drawing.Size(592, 249);
            //this.vdgvRecords.TabIndex = 2;
            //CommonFunctions.SetDataGridPrperties(vdgvRecords);
        }

        /// <summary>
        /// panel setting
        /// </summary>
        public override void Init()
        {
            InfoSetting();
            this.btnOk.Click += new RoutedEventHandler(btnOk_Click);
            this.btnCancel.Click += new RoutedEventHandler(btnCancel_Click);
            this.btnSelectAllButton.Click += new RoutedEventHandler(btnSelectAllButton_Click);
        }

        void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        void btnOk_Click(object sender, RoutedEventArgs e)
        {
            if (Save())
            {
               // this.DialogResult = true;
            }
        }

        /// <summary>
        /// on button click 
        /// this show all/zero selected records
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void btnSelectAllButton_Click(object sender, RoutedEventArgs e)
        {
            gridCount = 0;
            // select or deselect all as required
            //int rows = GlobalVariable.GridRowsCount(vdgvRecords);
            IList rowSource = vdgvRecords.ItemsSource as IList;
            int rows = rowSource.Count;
            //int rows = mainDataSet.Tables[0].Rows.Count;

            if (_checkStatus)
            {
                buttonImage = new Image();
                buttonImage.Source = Envs.LoadImageSource("checkedButton.PNG");
                btnSelectAllButton.Content = buttonImage;
                for (int i = 0; i < rows; i++)
                {
                    ((BindableObject)((ObservableCollection<object>)vdgvRecords.ItemsSource)[i]).SetValue("SELECTROW", _checkStatus.ToString().ToLower());
                    //mainDataSet.Tables[0].Rows[i]["SELECTROW"] = _checkStatus.ToString().ToLower();
                    vdgvRecords.SelectedIndex = i;
                    //((Grids.MyDataGridCheckBoxColumn)vdgvRecords.Columns[0]).SetCheckValue = _checkStatus;
                    CheckBox box = vdgvRecords.Columns[0].GetCellContent(vdgvRecords.SelectedItem) as CheckBox;
                    if (box != null)
                    {
                        box.IsChecked = _checkStatus;
                    }
                    gridCount++;
                }
                _checkStatus = false;

            }
            else
            {
                buttonImage = new Image();
                buttonImage.Source = Envs.LoadImageSource("UnCheked.PNG");
                btnSelectAllButton.Content = buttonImage;
                for (int i = 0; i < rows; i++)
                {
                    ((BindableObject)((ObservableCollection<object>)vdgvRecords.ItemsSource)[i]).SetValue("SELECTROW", _checkStatus.ToString().ToLower());
                    //mainDataSet.Tables[0].Rows[i]["SELECTROW"] = _checkStatus.ToString().ToLower();
                    // ((Grids.MyDataGridCheckBoxColumn)vdgvRecords.Columns[0]).SetCheckValue = _checkStatus;
                    vdgvRecords.SelectedIndex = i;
                    CheckBox box = vdgvRecords.Columns[0].GetCellContent(vdgvRecords.SelectedItem) as CheckBox;
                    if (box != null)
                    {
                        box.IsChecked = _checkStatus;
                    }
                }
                _checkStatus = true;
            }
            // Info(); 
            //vdgvRecords.ItemsSource = null;
            // vdgvRecords.ItemsSource = mainDataSet.Tables[0].GetBindableData(new Connector());
            statusBar.SetStatusLine(Msg.GetMsg(Envs.GetCtx(), "NumberOfSelectedRows") + gridCount.ToString());
        }
    }
}
